import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { getToken } from './index'
const request = axios.create({
  /* baseURL:process.env.Node_env === 'development'
  ?'/api'
  :'生产的源+/api' */
  baseURL: process.env.VUE_APP_BASEAPI
})
let loadingInstance = null
request.interceptors.request.use(function (config) {
  // 请求头添加token 做接口 token校验
  if (getToken()) {
    config.headers.token = getToken
  }
  loadingInstance = ElLoading.service({
    fullscreen: true,
    text: '加载中...',
    lock: true,
    background: 'rgba(0,0,0,0.7)'
  })
  return config
}, function (error) {
  loadingInstance.close()
  return Promise.reject(error)
})

request.interceptors.response.use(function (res) {
  // 判断后端返回 code码 做 登录过期 未登录处理
  switch (res.data.code) {
    case 401:
      ElMessage({
        type: 'error',
        message: '登录状态过期',
        duration: 2000
      })
      router.push('/login')
      store.commit('user/USER_GOOUT')
      break
    case 403:
      ElMessage({
        type: 'error',
        message: '用户未登录',
        duration: 2000
      })
      router.push('/login')
      store.commit('user/USER_GOOUT')
      break
  }
  loadingInstance.close()
  return res
}, function (error) {
  loadingInstance.close()
  return Promise.reject(error)
})

export default request
